package org.surelink.radius.server;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TBinaryProtocol.Factory;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.server.TThreadPoolServer.Args;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Autowired;
import org.surelink.radius.api.thrift.ApiService;
import org.surelink.radius.api.thrift.ApiServiceImpl;

import javax.annotation.PostConstruct;

public class ApiServer
{

    private static final Log log = LogFactory.getLog(ApiServer.class);

    @Autowired
    private ApiServiceImpl apiServiceImpl;

    private int port;

    public ApiServer(int port)
    {
        this.port = port;
    }

    @PostConstruct
    public void startServer()
    {
        try
        {

            TServerSocket serverTransport = new TServerSocket(port);

            ApiService.Processor process = new ApiService.Processor(apiServiceImpl);

            Factory portFactory = new TBinaryProtocol.Factory(true, true);

            Args args = new Args(serverTransport);
            args.processor(process);
            args.protocolFactory(portFactory);

            TServer server = new TThreadPoolServer(args);
            log.info("RADIUS接口服务器监听端口["+port+"]成功");
            server.serve();

        }
        catch (TTransportException e)
        {
            log.error("RadiusApiServer启动失败",e);
        }
    }
}
